#!/user/bin/env node

const log = console.log,
      http = require('http'),
      url = require('url'),
      qs = require('querystring'),
      fs = require('fs');

let items = [];

http.createServer((req,res)=>{
  //let path = url.parse(req.url).pathname;

  if(req.url !== '/'){
    res.statusCode = 404;
    err(res);
    log('4040 not found page');
    return;
  }
  log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  log('url:',req.url,req.method);
  log('header:',req.headers);

  switch(req.method){
    case'GET':
      show(res);
      break;
    case'POST':
      add(req,res);
      break;
    default:
      err(res);
      break;
  }
}).listen(3000);

function add(req,res){
  let body = '';
  req.on('data',(chunk)=>{
    body += chunk;
  })
  req.on('end',()=>{
    let item = qs.parse(body).item;
    if(item != ''){
      items.push(item);
    }
    show(res);
  })
}
  

function show(res){
  let html = fs.readFileSync('./11-template.html').toString('utf8');
  items_html = items.map(item => '<li>' + item + '</li>').join('\n');
  html = html.replace('%',items_html);
  res.writeHead(200,{
    'Content-Type':'text/html',
    'Content-Length':Buffer.byteLength(html),
    'Access-Control-Allow-Origin':'*'
  });
  res.end(html);
}

function err(res){
  let msg = 'not found!';
  res.statusCode = 404;
  res.setHeader('Content-Length',msg.length);
  res.setHeader('Content-Type','text/plain');
  res.end(msg);
}
